package com.glela.controller;

import com.alibaba.fastjson.JSON;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.StringUtil;
import com.glela.goods.model.MarketingActivities;
import com.glela.goods.model.MarketingActivitiesMain;
import com.glela.goods.model.request.MarketingActivitiesRequest;
import com.glela.goods.model.response.MarketingActivitiesGoodsDetailResponse;
import com.glela.goods.model.response.MarketingActivitiesMainResponse;
import com.glela.goods.service.MarketingActivitiesService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @ClassName: MarketingActivitiesController 
* @Description: 双11活动类控制器
* @author NingChongQing
* @date 2017年10月16日 上午11:37:22
 */
@Controller
@RequestMapping(value = "/marketingActivities")
public class MarketingActivitiesController {
	private static Logger logger = LoggerFactory.getLogger(MarketingActivitiesController.class);
	@Autowired
	private MarketingActivitiesService marketingActivitiesService;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private UserService userService;
	@Autowired
	private RedisUtil redisUtil;
	
	/**
	* **********************************************
	* @Title: homePage 
	* @Description: 双11首页列表
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月16日 下午4:40:59 
	* **********************************************
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/homePage", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> homePage(@RequestBody MarketingActivitiesRequest request) {
		try {
			Map<String, Object> map = null;
			try {
				String key = RedisKeys.MARKETING_ACTIV;
				String redisCache = redisUtil.get(key);
				if (StringUtil.isEmpty(redisCache)) {// redis没有缓存
					map = this.getMarketingActivities();
					// 将活动详情数据缓存到redis里面
					if (map != null) {
						redisUtil.setex(key, 900, JSON.toJSONString(map));
					}
				} else {// redis存在缓存，转换为map
					try {
						map = JsonUtil.toBean(redisCache, Map.class);
					} catch (Exception e) {// 类型转换报错了，redis里面的数据有问题，需要删除，map没值需要从数据库查一次
						redisUtil.del(key);
						map = this.getMarketingActivities();
					}
				}
			} catch (Exception e) {// Redis异常，map可能没有值，如果没值，需要重新从数据库查一次
				if (map == null) {
					map = this.getMarketingActivities();
				}
			}
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<双11首页列表>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	* **********************************************
	* @Title: getMarketingActivities 
	* @Description: 从数据库查询活动信息
	* @param @return 
	* @return Map<String,Object>
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月27日 下午4:41:31 
	* **********************************************
	 */
	public Map<String,Object> getMarketingActivities(){
		Map<String, Object> map = new HashMap<String, Object>();
		List<MarketingActivities> maList = this.marketingActivitiesService.selectFourMarketingActivitiesImages();
		List<Map<String,Object>> type2List = new ArrayList<Map<String,Object>>();
		Integer isDisplay = 0;
		// 服务器当前时间
		String backgroudImage = "";
		String activityTitle = "";
		Long beginTime = 0L; 
		Long endTime = 0L;
		long serverCurrentTime = System.currentTimeMillis();
		if (!CollectionUtils.isEmpty(maList)) {
			for(MarketingActivities ma: maList){
				if (ma.getType() == 1) {// 背景图片
					backgroudImage = ma.getImage();
					isDisplay = 1;
					activityTitle = ma.getText();
					beginTime = ma.getBeginTime().getTime();
					endTime = ma.getEndTime().getTime();
				} else if (ma.getType() == 2) {// 活动图片
					Map<String,Object> type2Map = new HashMap<String, Object>();
					type2Map.put("id", ma.getId());
					type2Map.put("image", ma.getUrl());
					type2Map.put("title", ma.getName());
					type2Map.put("isRedirect", ma.getIsRedirect());
					type2Map.put("redirectImgUrl", ma.getRedirectImgUrl() == null ? "" : ma.getRedirectImgUrl());
					type2List.add(type2Map);
				}
			}
		}
		map.put("isDisplay", isDisplay);
		map.put("backgroudImage", backgroudImage);
		map.put("activityTitle", activityTitle);
		map.put("beginTime", beginTime);
		map.put("endTime", endTime);
		map.put("marketingActivities", type2List.size() > 0 ? type2List : new ArrayList<Map<String,Object>>());
		map.put("serverCurrentTime", serverCurrentTime);
		return map;
	}
	
	/**
	* **********************************************
	* @Title: activePage 
	* @Description: 从数据库查或者从redis中取双11活动页详情信息
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月16日 下午5:08:36 
	* **********************************************
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/activePage", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> activePage(@RequestBody MarketingActivitiesRequest request) {
		try {
			if (ParameterUtils.validParams(request.getMarketingActivitiesId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			Integer marketingActivitiesId = request.getMarketingActivitiesId();
			// redis缓存key值：MAJOR校妆姐姐，GENERAL普通店铺
			String key = RedisKeys.MARKETING_ACTIV_INFO_MAJOR + marketingActivitiesId;
			// 校妆姐姐ID
			Integer xzJJUserId = Integer.valueOf(BaseConstants.XZ_SISTER+"");
			// 店主用户ID  默认校妆姐姐店铺的店主ID
			Integer storeUserId = xzJJUserId;
			if (!ParameterUtils.validParams(request.getUserId())) {
				User user = this.userService.getUserById(request.getUserId());
				User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
				storeUserId = storeUser.getId().intValue();
			}
			// 店主不是校妆姐姐 普通店主
			if (storeUserId.intValue() != xzJJUserId.intValue()) {
				key = RedisKeys.MARKETING_ACTIV_INFO_GENERAL + marketingActivitiesId;
			}
			Map<String, Object> map = null;
			try {
				String redisCache = redisUtil.get(key);
				if (StringUtil.isEmpty(redisCache)) {// redis没有缓存
					map = this.getMarketingActivitiesInfo(storeUserId,marketingActivitiesId);
					// 将活动详情数据缓存到redis里面
					if (map != null) {
						redisUtil.setex(key, 900, JSON.toJSONString(map));
					}
				} else {// redis存在缓存，转换为map
					try {
						map = JsonUtil.toBean(redisCache, Map.class);
					} catch (Exception e) {// 类型转换报错了，redis里面的数据有问题，需要删除，map没值需要从数据库查一次
						redisUtil.del(key);
						map = this.getMarketingActivitiesInfo(storeUserId,marketingActivitiesId);
					}
				}
			} catch (Exception e) {// Redis异常，map可能没有值，如果没值，需要重新从数据库查一次
				if (map == null) {
					map = this.getMarketingActivitiesInfo(storeUserId,marketingActivitiesId);
				}
			}
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<双11活动页列表>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	* **********************************************
	* @Title: getMarketingActivitiesInfo 
	* @Description: 从数据库查询双11活动页详情
	* @param @param storeUserId
	* @param @param marketingActivitiesId
	* @param @return 
	* @return Map<String,Object>
	* @throws	
	* @author NingChongQing	
	* @date 2017年10月27日 下午2:12:59 
	* **********************************************
	 */
	public Map<String, Object> getMarketingActivitiesInfo(Integer storeUserId, Integer marketingActivitiesId){
		// 活动类型
		String shareUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("share_url").getName();
		BaseRestrictions imageBR = this.baseRestrictionsService.getBaseRestrictionsForCache("image_url");
		String image_url = imageBR.getName();
		int size = imageBR.getExperience();
		Map<String, Object> map = new HashMap<String, Object>();
		MarketingActivities ma = this.marketingActivitiesService.selectById(marketingActivitiesId);
		List<MarketingActivitiesMain> mamList = this.marketingActivitiesService.selectByMarketingActivitiesId(marketingActivitiesId);
		if (!CollectionUtils.isEmpty(mamList) && ma != null) {
			List<MarketingActivitiesMainResponse> headers = new ArrayList<MarketingActivitiesMainResponse>();
			List<Map<String,Object>> lines = new ArrayList<Map<String,Object>>();
			for(MarketingActivitiesMain mam : mamList){
				List<MarketingActivitiesGoodsDetailResponse> magdrList = this.marketingActivitiesService.selectByPid(storeUserId,mam.getId());
				if (!CollectionUtils.isEmpty(magdrList)) {
					headers.add(new MarketingActivitiesMainResponse(mam));
					Map<String, Object> line = new HashMap<String, Object>();
					line.put("details", magdrList);
					line.put("image", mam.getImage()==null?"":mam.getImage());
					line.put("pId", mam.getId());
					lines.add(line);
				}
			}
			map.put("topImage", ma.getImage());
			map.put("topTitle", ma.getName());
			map.put("topImageWith", ma.getImageW() == null ? 0 : ma.getImageW());
			map.put("topImageHeight", ma.getImageH() == null ? 0 : ma.getImageH());
			map.put("shareUrl", shareUrl + "?id=" + ma.getId());
			map.put("shareImage", image_url + ma.getUrl() + "?imageView2/0/w/" + size + "/h/" + size);
			map.put("shareText", ma.getText());
			map.put("headers", headers);
			map.put("lines", lines);
		}
		return map;
	}
	/*-----------------------------------------------------------------------------------------------------*/
	/**
	 * @Description: 活动列表（新取类型为2的活动）-------暂弃用
	 * @Author: zhangrenjie
	 * @Date: 2018/1/10 13:19
	 *
	 */
	/*@SuppressWarnings("unchecked")
	@RequestMapping(value = "/activitiesGroup", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> ActivitiesGroup(@RequestBody RequestPageBaseModel request) {
		try {
			String phoneType = "";//客户端类型
			ReqHeaderVo reqHeader = request.getReqHeader();
			if (null != reqHeader) {
				phoneType = reqHeader.getPhoneType();
			}
			Map<String, Object> map = null;
			try {
				String key = RedisKeys.MARKETING_ACTIV_USETYPE_2;
				String redisCache = redisUtil.get(key);
				if (StringUtil.isEmpty(redisCache)) {
//					map = this.getActivitiesGroup();
					map = this.getActivitiesGroup(phoneType);
					if (map != null) {
						redisUtil.setex(key, 60*15, JSON.toJSONString(map));
					}
				} else {
					try {
						map = JsonUtil.toBean(redisCache, Map.class);
					} catch (Exception e) {// 类型转换报错了,map没值需要从数据库查一次
						redisUtil.del(key);
//						map = this.getActivitiesGroup();
						map = this.getActivitiesGroup(phoneType);
					}
				}
			} catch (Exception e) {// Redis异常，重新从数据库查一次
				if (null == map) {
//					map = this.getActivitiesGroup();
					map = this.getActivitiesGroup(phoneType);
				}
			}
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<活动列表>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}*/
	/**
	 * @Description: 查询类型为2的活动列表（暂弃用）
	 * @Author: zhangrenjie
	 * @Date: 2018/1/10 13:41
	 *
	 */
	/*private Map<String,Object> getActivitiesGroup(String phoneType) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<MarketingActivities> maList = this.marketingActivitiesService.queryMarketingActivitiesImages();
		List<Map<String,Object>> type2List = new ArrayList<Map<String,Object>>();
		Integer isDisplay = 0;String backgroudImage = "";String activityTitle = "";Long beginTime = 0L;Long endTime = 0L;
		long serverCurrentTime = System.currentTimeMillis();
		if (!CollectionUtils.isEmpty(maList)) {
			BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("h5_activity_url");
			if (null == baseRestrictions) {
				logger.error("---------跳转活动详情的H5访问域名为空，请检查数据库基础配置信息表-------");
				throw new RuntimeException("H5活动详情页访问域名为空，请检查数据库基础配置信息表");
			}
			String url = baseRestrictions.getName();
			for(MarketingActivities ma: maList){
				if (ma.getType() == 1) {// 背景图片
					backgroudImage = ma.getImage();
					isDisplay = 1;
					activityTitle = ma.getText();
					beginTime = ma.getBeginTime().getTime();
					endTime = ma.getEndTime().getTime();
				} else if (ma.getType() == 2) {// 活动图片
					Map<String,Object> type2Map = new HashMap<String, Object>();
					type2Map.put("skipUrl",url+"id="+ma.getId()+"&"+phoneType+"=1");
					type2Map.put("id", ma.getId());
					type2Map.put("image", ma.getUrl());
					type2Map.put("title", ma.getName());
					type2Map.put("isRedirect", ma.getIsRedirect());
					type2Map.put("redirectImgUrl", ma.getRedirectImgUrl() == null ? "" : ma.getRedirectImgUrl());
					type2List.add(type2Map);
				}
			}
		}
		map.put("isDisplay", isDisplay);
		map.put("backgroudImage", backgroudImage);
		map.put("activityTitle", activityTitle);
		map.put("beginTime", beginTime);
		map.put("endTime", endTime);
		map.put("marketingActivities", type2List.size() > 0 ? type2List : new ArrayList<Map<String,Object>>());
		map.put("serverCurrentTime", serverCurrentTime);
		return map;
	}*/
	/**
	 * @Description: 活动详情（新-根据活动父ID来查询活动详情）
	 * @Author: zhangrenjie
	 * @Date: 2018/1/10 15:19
	 *
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/activeInfoDetail", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> activeInfoDetail(@RequestBody MarketingActivitiesRequest request, HttpServletRequest r) {
		try {
			if (ParameterUtils.validParams(request.getMarketingActivitiesId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String phoneType = CommonConstants.PHONE_CLIENT_ANDROID;
			if (!StringUtils.isBlank(r.getHeader("phoneType"))) {
				phoneType = r.getHeader("phoneType").toLowerCase();
			}
			Integer marketingActivitiesId = request.getMarketingActivitiesId();
			// redis缓存key值：MAJOR校妆姐姐，GENERAL普通店铺
//			String key = RedisKeys.MARKETING_ACTIV_INFO_MAJOR + marketingActivitiesId;
			String key = RedisKeys.MARKETING_ACTIV_INFO_MAJOR + marketingActivitiesId+":"+phoneType;
			// 校妆姐姐ID
			Integer xzJJUserId = Integer.valueOf(BaseConstants.XZ_SISTER+"");
			// 店主用户ID  默认校妆姐姐店铺的店主ID
			Integer storeUserId = xzJJUserId;
			if (!ParameterUtils.validParams(request.getUserId())) {
				User user = this.userService.getUserById(request.getUserId());
				if (null != user) {
					User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
                    if (null != storeUser) {
                        storeUserId = storeUser.getId().intValue();
                    }
				}
			}
			// 店主不是校妆姐姐 普通店主
			if (storeUserId.intValue() != xzJJUserId.intValue()) {
//				key = RedisKeys.MARKETING_ACTIV_INFO_GENERAL + marketingActivitiesId;
				key = RedisKeys.MARKETING_ACTIV_INFO_GENERAL + marketingActivitiesId+":"+phoneType;
			}
			Map<String, Object> map = null;
			try {
				String redisCache = redisUtil.get(key);
				if (StringUtil.isEmpty(redisCache)) {// redis没有缓存
					map = this.getActivitiesInfoDetail(storeUserId,marketingActivitiesId,phoneType);
					if (map != null) {
						redisUtil.setex(key, 60*15, JSON.toJSONString(map));
					}
				} else {
					try {
						map = JsonUtil.toBean(redisCache, Map.class);
					} catch (Exception e) {// 类型转换报错了，map没值需要从数据库查一次
						redisUtil.del(key);
						map = this.getActivitiesInfoDetail(storeUserId,marketingActivitiesId,phoneType);
					}
				}
			} catch (Exception e) {// Redis异常，需要重新从数据库查一次
				if (map == null) {
					map = this.getActivitiesInfoDetail(storeUserId,marketingActivitiesId,phoneType);
				}
			}
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取<活动详情>异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	 * @Description: 活动详情（新）
	 * @Author: zhangrenjie
	 * @Date: 2018/1/10 15:22
	 *
	 */
	public Map<String, Object> getActivitiesInfoDetail(Integer storeUserId, Integer marketingActivitiesId,String phoneType){
//		String shareUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("share_url").getName();
		String shareUrl = this.baseRestrictionsService.getBaseRestrictionsForCache("h5_activity_url").getName();
		BaseRestrictions imageBR = this.baseRestrictionsService.getBaseRestrictionsForCache("image_url");
		String image_url = imageBR.getName();
		int size = imageBR.getExperience();
		Map<String, Object> map = new HashMap<String, Object>();
		MarketingActivities activitiesVo = null;
		MarketingActivities ma = this.marketingActivitiesService.selectById(marketingActivitiesId);
		if (null != ma) {
			//查询该活动的子活动ID（目前子只有一个，也是活动背景大图所在行）
			List<MarketingActivities> list = this.marketingActivitiesService.selectActivitiesByPid(ma.getId());
			if (!CollectionUtils.isEmpty(list)) {
				activitiesVo = list.get(0);
//				List<MarketingActivitiesMain> mamList = this.marketingActivitiesService.selectByMarketingActivitiesId(marketingActivitiesId);
				List<MarketingActivitiesMain> mamList = this.marketingActivitiesService.selectByMarketingActivitiesId(activitiesVo.getId());
//				if (!CollectionUtils.isEmpty(mamList) && ma != null) {
				if (!CollectionUtils.isEmpty(mamList)) {
					List<MarketingActivitiesMainResponse> headers = new ArrayList<MarketingActivitiesMainResponse>();
					List<Map<String,Object>> lines = new ArrayList<Map<String,Object>>();
					for(MarketingActivitiesMain mam : mamList){
						List<MarketingActivitiesGoodsDetailResponse> magdrList = this.marketingActivitiesService.selectActivitiesGoodsList(storeUserId,mam.getId());
						if (!CollectionUtils.isEmpty(magdrList)) {
							headers.add(new MarketingActivitiesMainResponse(mam));
							Map<String, Object> line = new HashMap<String, Object>();
							line.put("details", magdrList);
							line.put("image", mam.getImage()==null?"":mam.getImage());
							line.put("pId", mam.getId());
							lines.add(line);
						}
					}
					/*map.put("topImage", ma.getImage());
					map.put("topTitle", ma.getName());
					map.put("topImageWith", ma.getImageW() == null ? 0 : ma.getImageW());
					map.put("topImageHeight", ma.getImageH() == null ? 0 : ma.getImageH());
					map.put("shareUrl", shareUrl + "?id=" + ma.getId());
					map.put("shareImage", image_url + ma.getUrl() + "?imageView2/0/w/" + size + "/h/" + size);
					map.put("shareText", ma.getText());
					map.put("headers", headers);
					map.put("lines", lines);*/
					map.put("topImage", activitiesVo.getImage());
					map.put("topTitle", activitiesVo.getName());
					map.put("topImageWith", activitiesVo.getImageW() == null ? 0 : activitiesVo.getImageW());
					map.put("topImageHeight", activitiesVo.getImageH() == null ? 0 : activitiesVo.getImageH());
//					map.put("shareUrl", shareUrl + "id=" + ma.getId());//分享链接活动ID使用父ID
					map.put("shareUrl", shareUrl + "id="+ma.getId()+"&"+phoneType+"=1"+"&t="+System.currentTimeMillis());//分享链接活动ID使用父ID
					map.put("shareImage", image_url + activitiesVo.getUrl()==null?"":activitiesVo.getUrl() + "?imageView2/0/w/" + size + "/h/" + size);
					map.put("shareText", activitiesVo.getText());
					map.put("headers", headers);
					map.put("lines", lines);
				}
			}
		}
		return map;
	}

}
